package cyan.gf.generator;

import cyan.gf.util.PropReader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.Locale;
import java.util.Map;

/**
 * Created by cyan on 2017/2/19.
 * Email:qsyan@vip.qq.com
 */
public class FreemakerGenerator {

  private static String UTF8 = "UTF-8";
  private Configuration freemarkerCfg;
  private Template template;
  private File destFile;
  private Map map;

  public FreemakerGenerator(String ftl, String outFile) throws IOException {
    PropReader.load("/config/config.properties");
    String tempDir = System.getProperty("user.home") + PropReader.getString("app.templeteDir");
    freemarkerCfg = new Configuration(Configuration.VERSION_2_3_22);
    freemarkerCfg.setDirectoryForTemplateLoading(new File(tempDir));
    freemarkerCfg.setEncoding(Locale.getDefault(), UTF8);
    template = freemarkerCfg.getTemplate(ftl, UTF8);
    template.setOutputEncoding(UTF8);
    template.setClassicCompatible(true);
    destFile = new File(outFile);
  }

  public void setData(Map map) {
    this.map = map;
  }

  public void process() throws IOException, TemplateException {
    Writer out = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(destFile), UTF8));
    template.process(map, out);
    out.flush();
    out.close();
  }
}
